<template>
  <div>
    <el-drawer title="订单编辑" v-model="visible" :size="1000" >
      <template #header>
        <div class="flex items-center title">
          <div class="w-[5px] h-[5px] rounded-[50%] bg-[#3721FF] mr-[10px] circle"></div>
          <div class="tits">订单编辑</div>
        </div>
      </template>
      <div class="w-full h-[1px] bg-[#EFEFEF] line"></div>
      <div class="pt-[30px]">
        <el-form
          ref="formRef"
          :model="form"
          label-width="150"
          :rules="rules"
          :validate-on-rule-change="false"
        >
          <div
            class="bg-[#FAFAFA] py-[18px] px-[24px] rounded-[8px] text-[#101010] text-[14px] relative z-2 baseinfo"
          >
            订单号：{{ form?.orderNo }}
          </div>
          <div class="relative top-[-5px] z-1 block" style="border-radius: 0 0 8px 8px">
            <div class="text-[#101010] text-[14px] relative font-semibold pl-[10px] tit">
              基本信息
            </div>
            <div class="flex justify-between items-center mt-[20px]">
              <div class="flex items-center items">
                <div class="label">
                  <span class="red">*</span>
                  <span>地区：</span>
                </div>
                <div class="text-[#666] val">{{ form.areaName }}</div>
              </div>
              <div class="flex items-center items">
                <div class="label">
                  <span class="red">*</span>
                  <span>下单时间：</span>
                </div>
                <div class="text-[#666] val">{{ formatDate(form.createTime) }}</div>
              </div>
              <div class="flex items-center items">
                <div class="label">
                  <span class="red">*</span>
                  <span>订单状态：</span>
                </div>
                <div class="val">
                  <div class="flex justify-center items-center statusbox">
                    <div
                      class="px-[7px] py-[2px] flex items-center rounded-[5px]"
                      :style="`background-color:${orderStatus[Number(form.status)].bgColor}`"
                    >
                      <div class="w-[12px] h-[12px] rounded-[50%] relative mr-[4px] icon">
                        <img
                          :src="orderStatus[Number(form.status)].icon"
                          class="w-full h-full object-contain absolute top-0 left-0"
                        />
                      </div>
                      <div
                        class="text-[12px] status txt"
                        :style="`color:${orderStatus[Number(form.status)].color}`"
                      >
                        {{ orderStatus[Number(form.status)].name }}</div
                      >
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="block" style="margin-top: 24px">
            <div class="text-[#101010] text-[14px] relative font-semibold pl-[10px] tit">
              客户信息
            </div>
            <div class="mt-[30px] formbox">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item prop="customerName">
                    <template #label>
                      <div class="labelbox">
                        <span>姓名：</span>
                      </div>
                    </template>
                    <el-input v-model="form.customerName" placeholder="请输入姓名" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="customerPhone">
                    <template #label>
                      <div class="labelbox">
                        <span>电话号码：</span>
                      </div>
                    </template>
                    <el-input v-model="form.customerPhone" placeholder="请输入电话号码" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item>
                    <template #label>
                      <div class="labelbox">
                        <span>WhatsApp：</span>
                      </div>
                    </template>
                    <el-input v-model="form.whatsapp" placeholder="请输入WhatsApp帐号" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item>
                    <template #label>
                      <div class="labelbox">
                        <span>line：</span>
                      </div>
                    </template>
                    <el-input v-model="form.line" placeholder="请输入line帐号" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item>
                    <template #label>
                      <div class="labelbox">
                        <span>IP：</span>
                      </div>
                    </template>
                    <div>{{ form.ipAddress }}</div>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item>
                    <template #label>
                      <div class="labelbox">
                        <span>邮箱：</span>
                      </div>
                    </template>
                    <el-input v-model="form.email" placeholder="请输入邮箱" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item>
                    <template #label>
                      <div class="labelbox">
                        <span>物流方式：</span>
                      </div>
                    </template>
                    <el-select
                      v-model="form.logisticsMethod"
                      placeholder="请选择物流方式"
                      @change="changeLogisticsMethod"
                    >
                      <el-option
                        v-for="(item, index) in sendMethodList"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item prop="addressArr">
                    <template #label>
                      <div class="labelbox">
                        <span>地址：</span>
                      </div>
                    </template>
                    <!-- <el-input v-model="form.address" placeholder="请输入姓名" /> -->
                    <el-cascader
                      v-model="form.addressArr"
                      :options="areaList"
                      class="w-full"
                      @change="handleAddressArr"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-if="showStoreAddress">
                  <el-form-item prop="address">
                    <template #label>
                      <div class="labelbox">
                        <span>门店地址：</span>
                      </div>
                    </template>
                    <!-- <el-input v-model="form.address" placeholder="请输入姓名" /> -->
                    <el-select v-model="form.addressId" placeholder="请选择门店">
                      <el-option
                        v-for="(item, index) in storeList"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item prop="detailAddress">
                    <template #label>
                      <div class="labelbox">
                        <span>详细地址：</span>
                      </div>
                    </template>
                    <el-input v-model="form.detailAddress" placeholder="请输入详细地址" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item>
                    <template #label>
                      <div class="labelbox">
                        <span>门牌号/建筑物名称：</span>
                      </div>
                    </template>
                    <el-input v-model="form.houseNumber" placeholder="请输入门牌号/建筑物名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item>
                    <template #label>
                      <div class="labelbox">
                        <span>邮编：</span>
                      </div>
                    </template>
                    <el-input v-model="form.name" placeholder="请输入邮箱" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item>
                    <template #label>
                      <div class="labelbox">
                        <span>留言：</span>
                      </div>
                    </template>
                    <el-input v-model="form.message" placeholder="请输入留言" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item >
                    <template #label>
                      <div class="labelbox">
                        <span>备注：</span>
                      </div>
                    </template>
                    <el-input v-model="form.remark" placeholder="请输入备注" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
          <div class="block" style="margin-top: 24px">
            <div class="text-[#101010] text-[14px] relative font-semibold pl-[10px] tit">
              商品信息
            </div>
            <div
              class="pb-[20px] productItem"
              v-for="(item, index) in form.detailList"
              :key="index"
              v-loading="loading"
            >
              <div class="mt-[15px] relative formbox" v-if="index==0">
                <div class="absolute right-0 z-1 cursor-pointer" v-if="item.isAdd">
                  <Icon icon="ep:delete" color="#f00" @click="deleteProduct(index)" />
                </div>
                <el-row :gutter="20" style="padding: 6px 0">
                  <el-col :span="12">
                    <div class="flex item">
                      <div class="label shrink-0">
                        {{ `${form.thaliId ? '套餐名称：' : '商品名称：'}` }}
                      </div>
                      <div class="text-[#666] val">{{ form.thaliId ? form.thaliName : item.productName }}</div>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="flex item">
                      <div class="label shrink-0">币种：</div>
                      <div class="text-[#666] val">{{ form.currency }}</div>
                    </div>
                  </el-col>
                </el-row>
                <el-row :gutter="20" style="padding: 6px 0" v-if="form.thaliId">
                  <el-col :span="12">
                    <div class="flex item">
                      <div class="label shrink-0">套餐价格：</div>
                      <div class="text-[#666] val">{{ form.currencySymbol }} {{ form.thaliPrice }}</div>
                    </div>
                  </el-col>
                </el-row>
              </div>
              <div class="mt-[30px] goods">
                <div class="mb-[10px]">商品名称：<span class="text-[#999]">{{ item.productName }}</span> </div>
                <div
                  class="bg-[#F7F7FB] flex rounded-[10px] py-[17px] px-[24px] relative z-2 header"
                >
                  <div class="items" style="flex: 0 0 9%; flex-shrink: 0">图片</div>
                  <div class="items" style="flex: 0 0 25%; flex-shrink: 0">规格</div>
                  <div class="items" style="flex: 0 0 17%; flex-shrink: 0">sku</div>
                  <div class="items" style="flex: 0 0 13%; flex-shrink: 0">数量</div>
                  <div class="items" style="flex: 0 0 13%; flex-shrink: 0">单价</div>
                  <div class="items" style="flex: 0 0 13%; flex-shrink: 0">总价</div>
                  <div class="items" style="flex: 0 0 10%; flex-shrink: 0">操作</div>
                </div>
                <div
                  class="px-[24px] pb-[17px] pt-[23px] flex flex-col relative top-[-6px] items-center"
                  style="border: 1px solid #f7f7fb; border-radius: 0 0 10px 10px"
                >
                  <div
                    class="w-full py-[10px] flex itemsbox"
                    v-for="(subitem, subindex) in item.specifications"
                    :key="subindex"
                  >
                    <div class="items" style="flex: 0 0 9%; flex-shrink: 0">
                      <div class="w-[38px] h-[38px] rounded-[6px] overflow-hidden imgbox">
                        <img :src="subitem.picture" class="w-full h-full object-cover" />
                      </div>
                    </div>
                    {{ subitem }}
                    <div class="items" style="flex: 0 0 25%; flex-shrink: 0">
                      <el-select
                        v-model="subitem.propertyValueSku"
                        placeholder="请选择"
                        style="width: 80%"
                        @change="changeSpecification(index, subindex, subitem.productId)"
                        :disabled="!subitem.isAdd"
                      >
                        <el-option
                          v-for="items in getTypeList(subitem.productId)"
                          :key="items.propertyValue"
                          :label="items.propertyValue"
                          :value="items.sku"
                          :disabled="items.disabled"
                        />
                      </el-select>
                      <!-- <div class="text-[12px] text-[#999] tips">
                        {{ getTypeName(subitem.productId) }}
                      </div> -->
                    </div>
                    <div class="items" style="flex: 0 0 17%; flex-shrink: 0">
                      <el-tooltip
                        class="box-item"
                        effect="dark"
                        :content="subitem.propertyValueSku"
                        placement="top"
                      >
                        <div
                          class="cursor-pointer"
                          v-copyText="subitem.propertyValueSku"
                          v-if="subitem.propertyValueSku"
                        >
                          {{ subitem.propertyValueSku }}
                          <Icon icon="ep:copy-document" :size="12" class="cursor-pointer" />
                        </div>
                      </el-tooltip>
                    </div>
                    <div class="items" style="flex: 0 0 13%; flex-shrink: 0">
                      <el-input-number
                        v-model="subitem.number"
                        :min="1"
                        :max="10"
                        style="width: 90%"
                        @change="changeNumber(index, subindex)"
                      />
                      <!-- :disabled="!subitem.isAdd || !subitem.propertyValueSku" -->
                    </div>
                    <div class="items" style="flex: 0 0 13%; flex-shrink: 0">
                      <div class="o" v-if="subitem.discountedPrice">
                        折扣价：{{ form.currencySymbol }}{{ subitem.discountedPrice || '-' }}
                      </div>
                      <div
                        class="text-[12px] text-[#999]  o"
                        :class="subitem.discountedPrice?'line-through':''"
                        v-if="subitem.originalPrice"
                      >
                        原价：{{ form.currencySymbol }}{{ subitem.originalPrice || '-' }}
                      </div>
                    </div>
                    <div class="items" style="flex: 0 0 13%; flex-shrink: 0">
                      <div v-if="subitem.totalPrice">
                        {{ form.currencySymbol }} {{ subitem.totalPrice ? Number(subitem.totalPrice).toFixed(2):'-' }}</div
                      >
                    </div>
                    <div class="items" style="flex: 0 0 10%; flex-shrink: 0">
                      <div class="cursor-pointer" v-if="subitem.isAdd">
                        <Icon
                          icon="ep:delete"
                          color="#f00"
                          @click="deleteSubItem(index, subindex)"
                        />
                      </div>
                      <div v-else> - </div>
                    </div>
                  </div>
                </div>

                <div
                  class="mt-[24px] flex items-center cursor-pointer text-[#3721ff] btnbox"
                  @click="handleAddType(index, item.productId)"
                  v-if="
                    item.specifications &&
                    item.specifications.length < Number(getTypeList(item.productId)?.length)
                  "
                >
                  <Icon icon="ep:plus" :size="12" class="mr-[4px] cursor-pointer" />
                  添加规格值
                </div>
              </div>
            </div>
          </div>
          <el-button
            class="mt-[25px] w-[108px]"
            type="primary"
            color="#3721FF"
            style="border-radius: 6px !important"
            @click="handleselectProducts"
          >
            <Icon icon="ep:plus" :size="12" class="cursor-pointer" />
            添加商品
          </el-button>
          <div class="mt-[40px]">
            <div class="flex items-center justify-end py-[7px] items">
              <div class="lable"> + 商品金额：{{ form.currencySymbol }} </div>
              <div class="ml-[20px] val">
                <el-input
                  v-model="form.orderProductAmount"
                  type="number"
                  placeholder="请输入商品金额"
                  style="width: 152px"
                />
              </div>
            </div>
            <div class="flex items-center justify-end py-[7px] items">
              <div class="lable">+ 订单运费：{{ form.currencySymbol }}</div>
              <div class="ml-[20px] val">
                <el-input
                  v-model="form.orderFreight"
                  type="number"
                  placeholder="请输入订单运费"
                  style="width: 152px"
                />
              </div>
            </div>
            <div class="flex items-center justify-end py-[7px] items">
              <div class="lable">+ 手续费：{{ form.currencySymbol }}</div>
              <div class="ml-[20px] val">
                <el-input
                  v-model="form.serviceCharge"
                  type="number"
                  placeholder="请输入手续费"
                  style="width: 152px"
                />
              </div>
            </div>
            <!-- <div class="flex items-center justify-end py-[7px] items">
              <div class="lable">+ 消费税：{{ form.currencySymbol }}</div>
              <div class="ml-[20px] val">
                <el-input
                  v-model="form.consumptionTax"
                  type="number"
                  placeholder="请输入消费税"
                  style="width: 152px"
                />
              </div>
            </div> -->
            <div class="flex items-center justify-end py-[7px] items">
              <div class="lable">- 折扣：{{ form.currencySymbol }}</div>
              <div class="ml-[20px] val">
                <el-input
                  v-model="form.discount"
                  type="number"
                  placeholder="请输入折扣金额"
                  style="width: 152px"
                />
              </div>
            </div>
            <div class="flex items-center justify-end py-[7px] items">
              <div class="lable">  订单总金额：{{ form.currencySymbol }} </div>
              <div class="ml-[20px] val">
                <el-input
                  v-model="form.orderAmount"
                  type="number"
                  placeholder="请输入商品金额"
                  style="width: 152px"
                  :disabled="true"
                />
              </div>
            </div>
          </div>
        </el-form>
      </div>
      <template #footer>
        <div class="drawer-footer">
          <el-button class="w-[108px] h-[45px] rounded-[10px] text-[12px]" @click="hide"
            >取消</el-button
          >
          <el-button
            class="w-[108px] h-[45px] rounded-[10px] text-[12px]"
            type="primary"
            color="#3721ff"
            @click="submit"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>
    <SelectProducts
      ref="selectProductsRef"
      :showDot="true"
      width="50%"
      title="选择商品"
      @confirm="handleUpdateSelProductList"
    />
  </div>
</template>

<script setup lang="ts">
import { FormInstance, valueEquals } from 'element-plus'
import { orderStatus } from '@/utils/order'
import * as TradeOrderApi from '@/api/mall/trade/order'
import { formatDate } from '@/utils/formatTime'
import { ProductApi } from '@/api/product/addProduct'
import { GlobeStateMethodApi } from '@/api/method'
import { GlobeStateDetailApi, GlobeStateDetailVO } from '@/api/globestatedetail'
import { usePageLoading } from '@/hooks/web/usePageLoading'

const { loadStart, loadDone } = usePageLoading()

const message = useMessage() // 消息弹窗

const emit = defineEmits(['updateList'])

type ProductTypes = {
  id: number | string
  types: any[]
}

const props = defineProps({
  editOrderNo: {
    type: [String, Number],
    required: true,
    default: ''
  }
})

const loading = ref(false)

const orderDetails = ref<TradeOrderApi.ProductOrderGetRespVO>({})

const form = ref<TradeOrderApi.ProductOrderGetRespVO>({
  address: '',
  consumptionTax: undefined,
  customerName: '',
  customerPhone: '',
  detailAddress: '',
  detailList: [],
  discount: undefined,
  email: '',
  houseNumber: '',
  ipAddress: '',
  line: '',
  logisticsMethod: undefined,
  message: '',
  orderAmount: undefined,
  orderFreight: undefined,
  orderNo: undefined,
  remark: '',
  serviceCharge: undefined,
  status: 0,
  whatsapp: '',
  currency: undefined
})

const rules = {
  customerName: [
    {
      required: true,
      message: '请输入客户姓名',
      trigger: 'blur'
    }
  ],
  customerPhone: [
    {
      required: true,
      message: '请输入客户电话',
      trigger: 'blur'
    }
  ],
  address: [
    {
      required: true,
      message: '请输入地址',
      trigger: 'blur'
    }
  ],
  detailAddress: [
    {
      required: true,
      message: '请输入详细地址',
      trigger: 'blur'
    }
  ]
}

const goodsTypeList = ref<ProductTypes[]>([]) //商品规格选项，页面会涉及多个商品

const areaList = ref<any>([])

const storeList = ref<any>([])

const originAreaList = ref<any>([])

const sendMethodList = ref<any>([])

const selectProductsRef = ref<any | null>(null)

const visible = ref(false)

const customerShow = ref(false)

const showStoreAddress = ref(false)

const formRef = ref<FormInstance | null>(null)

const addGoods = ref();

/**
 * 详情中是否显示客户信息
 */
const handleCustomerShow = () => {
  customerShow.value = !customerShow.value
}

/**
 * 提交数据
 */
const submit = () => {
  formRef.value?.validate(async (bool) => {
    if (bool) {
      if (form.value.detailList) {
        form.value.detailList = convertTo1DArray(form.value.detailList)
      }
      if (form.value.addressArr) {
        form.value.areaName = form.value.addressArr[0]
        form.value.cityName = form.value.addressArr[1]
        form.value.regionName = form.value.addressArr[2]
      }
      try {
        loadStart()
        await TradeOrderApi.updateOrderDetails(form.value)
        emit('updateList')
        hide()
      } finally {
        loadDone()
      }
    }
  })
}

/**
 * 将detailList根据商品ID转换为二维数组
 */
const convertTo2DArray = (detailList) => {
  const result = {}

  detailList.forEach((item) => {
    const { id, productId } = item
    if (!result[id]) {
      result[id] = {
        ...item,
        specifications: [] // 初始化规格数组
      }
    }
    result[id].specifications.push(item)
  })

  return Object.values(result).map((item) => ({
    id: item.id,
    productId: item.productId,
    productName: item.productName,
    thaliPrice: item.thaliPrice, //套餐价格
    thaliName: item.thaliName, //套餐名称
    thaliFlag: item.thaliFlag, //是否是套餐 0:否 1:是
    specifications: item.specifications,
  }))
}

/**
 * 将detailList由二维数组转换成一维数组
 */
const convertTo1DArray = (twoDArray) => {
  const result = []

  twoDArray.forEach((item) => {
    item.specifications.forEach((spec) => {
      result.push(spec)
    })
  })

  return result
}

/**
 * 添加规格值
 */
const handleAddType = (index: number, id: string) => {
  if (form.value.detailList) {
    const typeList = goodsTypeList.value.find((item) => item.id === id)?.types
    form.value.detailList[index].specifications.push({
      id:  form.value.detailList[index].specifications[0].id,
      productId: form.value.detailList[index].specifications[0].productId,
      productName: form.value.detailList[index].specifications[0].productName,
      thaliId: form.value.detailList[index].specifications[0].thaliId,
      thaliName: form.value.detailList[index].specifications[0].thaliName,
      currency: form.value.detailList[index].specifications[0].currency,
      thaliPrice: form.value.detailList[index].specifications[0].thaliPrice,
      picture: form.value.detailList[index].specifications[0].picture,
      number: 1,
      originalPrice: null,
      discountedPrice: null,
      totalPrice: null,
      propertyValueName: undefined,
      propertyValueSku: undefined,
      isAdd: true
    })
  }
}

/**
 * 删除新增加的规格
 */
const deleteSubItem = async (index: number, subIndex: number) => {
  if (form.value.detailList) {
    await message.delConfirm()
    form.value.detailList[index].specifications.splice(subIndex, 1)
  }
}

/**
 * 删除新添加的商品
 */
const deleteProduct = async (index: number) => {
  if (form.value.detailList) {
    await message.delConfirm()
    form.value.detailList.splice(index, 1)
  }
}

/**
 * 获取商品规格
 */
const getProductsGoods = async (id: number | string) => {
  try {
    const res = await ProductApi.getByProductId({ productId: id })
    const findIndex = goodsTypeList.value.findIndex((item) => item.id === id)
    const temp = res.filter((item) => item.saleFlag)
    if (findIndex !== -1) {
      goodsTypeList.value[findIndex].types = temp
    } else {
      goodsTypeList.value.push({ id, types: temp })
    }
  } catch (error) {}
}
/**
 * 根据商品ID，从goodsTypeList筛选出对应的商品规格
 * @param id
 */
const getTypeList = (id: number | string) => {
  if (goodsTypeList.value.length) {
    const typeList = goodsTypeList.value.find((item) => item.id === id)?.types

    if (typeList) {
      //筛选出已经选中的规格
      const selectedSpec = form.value.detailList?.find(
        (item) => item.productId === id
      )?.specifications
      if (selectedSpec) {
        typeList.forEach((item) => {
          if (selectedSpec.find((spec) => spec.propertyValueSku === item.propertyValueSku)) {
            item.disabled = true
          } else {
            item.disabled = false
          }
          item.propertyValueSku = item.sku
        })
      }
      return typeList
    } else {
      return null // 或者根据需要返回其他值
    }
  }
  return null // 或者根据需要返回其他值
}
/**
 * 根据商品规格ID，从typeList筛选出对应的商品规格提示名称
 */
const getTypeName = (id: number | string) => {
  if (goodsTypeList.value && goodsTypeList.value.length) {
    const typeList = goodsTypeList.value.find((item) => item.id === id)?.types
    if (typeList && typeList.length) {
      return typeList[0].name || ''
    }
  } else {
    return ''
  }
}

/**
 * 规格变化时需要更新sku,原件,折扣等信息
 */
const changeSpecification = (index: number, subindex: number, productId: number) => {
  // 获取当前商品的规格（可能多商品）
  const typesList = getTypeList(productId)
  const detailList = form.value.detailList
  if (detailList) {
    const specification = detailList[index].specifications[subindex]
    const propertyValue = specification.propertyValueSku

    // 查找对应的类型
    const foundType = typesList?.find((item) => item.propertyValueSku === propertyValue)
    if (foundType) {
      // 更新规格信息
      specification.propertyValueSku = foundType.sku
      specification.originalPrice = foundType.price
      specification.discountedPrice = foundType.discountedPrice
      specification.totalPrice = foundType.discountedPrice? Number(foundType.discountedPrice * specification.number).toFixed(2)   : Number(foundType.price * specification.number).toFixed(2)// 计算总价
      //价格合计
      getTotalPrice()
    }
  }
}

/**
 * 数量变化时，重新计算价格
 *
 * */
const changeNumber = (index: number, subindex: number) => {
  const detailList = form.value.detailList
  if (detailList) {
    const specification = detailList[index].specifications[subindex]
    console.log('specification==================', specification)
    if (!specification.propertyValueSku) {
      message.error('请先选择规格')
      return
    }
    specification.totalPrice = specification.discountedPrice? specification.discountedPrice * specification.number : specification.originalPrice * specification.number // 计算总价
    //价格合计
    // getTotalPrice()
  }
}

/**
 * 计算价格合计
 */
const getTotalPrice = () => {
  const detailList = form.value.detailList
  if (detailList) {
    let totalPrice = 0
    detailList.forEach((item) => {
      item.specifications.forEach((specification) => {
        totalPrice += specification.totalPrice
      })
    })
    form.value.orderAmount = totalPrice
  }
}

/**
 * 显示选择商品弹窗
 */
const handleselectProducts = () => {
  selectProductsRef.value?.show()
}

/**
 * 选择商品后，更新商品列表
 */
const handleUpdateSelProductList =  (val) => {
  //检查新添加的商品是否已存在
  addGoods.value = val
  form.value.detailList?.findIndex((item) => {
    val.map((subitem) => {
      if (item.productId === subitem.id) {
        message.error(`商品 '${subitem.title}' 已存在`)
        return
      }
    })
  })
  
   


  //将选中的商品添加到detailList中,需要查询商品的规格选项列表
  val.forEach(async (item) => {
    await getProductsGoods(item.id)
    const valTypes = goodsTypeList.value.findIndex((item)=>{item.id === val[0].id})
    
    form.value.detailList?.push({
      productId: item.id,
      productName: item.title,
      picture: item.cover,
      isAdd: true,
      specifications: [
        {
          isAdd:true,
          number: 1,
          totalPrice: item.discountedPrice || item.originalPrice || 0,
          picture: item.cover,
          productId: item.id,
          propertyValueName: '',
          propertyValueSku: '',
          discountedPrice: item.discountedPrice || 0,
          originalPrice: item.originalPrice || 0
        }
      ]
    })
  })
}

watch(
  ()=>[form.value.orderProductAmount,form.value.orderFreight,form.value.serviceCharge,form.value.discount],
  ()=>{
    form.value.orderAmount = Number(form.value.orderProductAmount) + Number(form.value.orderFreight) + Number(form.value.serviceCharge) - Number(form.value.discount)
  }
)


// 监听 orderNo 的变化
// watch(
//   () => props.editOrderNo,
//   async (newOrderNo) => {
//     if (newOrderNo && visible.value) {
//       try {
//         // 通过接口获取订单详情
//         const response = await TradeOrderApi.getOrderDetails(props.editOrderNo)
//         // orderDetails.value = response
//         form.value = response
//         if (form.value.logisticsMethod)
//           form.value.logisticsMethod = Number(form.value.logisticsMethod) //将物流方式转换为数字类型
//         if (form.value.addressId) form.value.addressId = Number(form.value.addressId) //将地址id转换为数字类型
//         form.value.addressArr = [form.value.areaName, form.value.cityName, form.value.regionName]
//         await getMethod(form.value.areaId) //获取物流方式
//         //获取到物流方式后，需要判断该物流方式是否显示门店地址
//         showStoreAddress.value =
//           sendMethodList.value.find((item) => item.value == form.value.logisticsMethod)
//             ?.directlyStatus === 0
//         await getAddressList(form.value.areaId) //获取收货地址列表
//         //获取地区的门店列表
//         await getStoreList(form.value.addressArr)
//         if (form.value.detailList) {
//           form.value.detailList = convertTo2DArray(form.value.detailList)
//           form.value.detailList.forEach((item) => {
//             getProductsGoods(item.productId)
//           })
//         }
//       } catch (error) {
//         console.error('获取订单详情失败:', error)
//       }
//     }
//   },
//   { immediate: true, deep: true }
// )

const getDetails = async () => {
  try {
    loading.value = true
    // 通过接口获取订单详情
    const response = await TradeOrderApi.getOrderDetails(props.editOrderNo)
    // orderDetails.value = response
    form.value = response
    if (form.value.logisticsMethod) form.value.logisticsMethod = Number(form.value.logisticsMethod) //将物流方式转换为数字类型
    if (form.value.addressId) form.value.addressId = Number(form.value.addressId) //将地址id转换为数字类型
    form.value.addressArr = [form.value.areaName, form.value.cityName, form.value.regionName]
    await getMethod(form.value.areaId) //获取物流方式
    //获取到物流方式后，需要判断该物流方式是否显示门店地址
    showStoreAddress.value =
      sendMethodList.value.find((item) => item.value == form.value.logisticsMethod)
        ?.directlyStatus === 0
    await getAddressList(form.value.areaId) //获取收货地址列表
    //获取地区的门店列表
    await getStoreList(form.value.addressArr)
    if (form.value.detailList) {
      form.value.detailList = convertTo2DArray(form.value.detailList)
      form.value.detailList.forEach((item) => {
        getProductsGoods(item.productId)
      })
    }
  } finally{
    loading.value = false
  }
}

// 获取门店列表
const getStoreList = async (addressArr) => {
  //先获取地区id
  const areaInfo = originAreaList.value.find((item) => {
    if (
      item.stateName === addressArr[0] &&
      item.province === addressArr[1] &&
      item.city === addressArr[2]
    ) {
      return item
    }
  })
  if (!areaInfo) return []
  let res = await GlobeStateDetailApi.getGlobeStateStoreList({
    // detailStateId: areaInfo.id,
    name: areaInfo.city,
    methodId: form.value.logisticsMethod
  })
  storeList.value = res.map((item) => {
    return {
      label: item.storeName,
      value: item.id
    }
  })
}

// 获取地址列表信息
const getAddressList = async (areaId) => {
  let res = await GlobeStateDetailApi.getGlobeStateDetailPage({pageNum:1,pageSize:1000, stateId: areaId })
  originAreaList.value = res.list
  areaList.value = transformList(res.list)
}

/**
 * 获取该地区的 物流方式
 */
const getMethod = async (areaId) => {
  let res = await GlobeStateMethodApi.getGlobeStateMethodPage({
    stateId: areaId
  })
  sendMethodList.value = res.list.map((item) => {
    return {
      label: item.methodName,
      value: item.id,
      directlyStatus: item.directlyStatus
    }
  })
}
/**
 * 组装省份数据为三级结构
 */
 const transformList = (data) => {
  const result = [];

  data.forEach((item) => {
    // 查找或创建省节点
    let provinceNode = result.find((province) => province.label === item.stateName);
    if (!provinceNode) {
      provinceNode = { label: item.stateName, value: item.stateName, children: [] };
      result.push(provinceNode);
    }

    // 查找或创建市节点
    let cityNode = provinceNode.children.find((city) => city.label === item.province);
    if (!cityNode) {
      cityNode = { label: item.province, value: item.province, children: [] };
      provinceNode.children.push(cityNode);
    }

    // 添加区域信息，确保区信息不为空
    if (item.city) {
      cityNode.children.push({ label: item.city, value: item.city });
    }
  });

  return result;
};
/**
 * 物流方式，需要重新获取门店列表
 */
const changeLogisticsMethod = () => {
  showStoreAddress.value =
    sendMethodList.value.find((item) => item.value === form.value.logisticsMethod)
      ?.directlyStatus === 0
  form.value.addressId = undefined
  form.value.address = ''
  if (showStoreAddress.value) {
    getStoreList(form.value.addressArr)
  }
}

/**
 * 地址变化时，需要重新获取门店列表
 */
const handleAddressArr = () => {
  form.value.detailAddress = ''
  form.value.addressId = undefined
  form.value.address = ''
  getStoreList(form.value.addressArr)
}

const show = () => {
  visible.value = true
  nextTick(() => {
    getDetails()
  })
}

const hide = () => {
  visible.value = false
}

defineExpose({
  show,
  hide
})
</script>

<style lang="scss" scoped>
:deep(.el-drawer__header) {
  margin-bottom: 0px;
}
.productItem {
  border-bottom: 1px solid #e4e4e4;
  &:last-child {
    border-bottom: none;
  }
}
.tit {
  &::before {
    content: '';
    width: 2px;
    height: 7px;
    position: absolute;
    top: 8px;
    left: 0px;
    background: #3721ff;
    border-radius: 0 2px 2px 0;
    display: block;
    z-index: 1;
  }
}
.block {
  border: 1px solid #e4e4e4;
  border-radius: 8px;
  background-color: #fff;
  padding: 30px 24px;
}
:deep(.el-button) {
  height: 40px !important;
  border-radius: 10px !important;
}
:deep(.el-button span) {
  font-size: 12px;
}
:deep(.el-drawer__footer) {
  padding-top: 24px;
  border-top: 1px solid #e4e4e4;
}
</style>
